package com.kui.manager.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import com.kui.exception.BusinessException;
import com.kui.exception.ErrorCode;
import com.kui.exception.ThrowUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

@Service
public class UrlUpload extends FileUploadTemplate {
    @Override
    protected void processFile(Object inputSource, File file) {
        String url = (String) inputSource;
        try {
            HttpUtil.downloadFile(url, file);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件下载失败");
        }
    }

    @Override
    protected String getOriginalFilename(Object inputSource) {
        String url = (String) inputSource;
//        拿到url中的最后一个.的索引方便取到后缀名
        int indexOf = url.lastIndexOf('.');
        String substring = url.substring(indexOf);
        String s = FileNameUtil.mainName(url);
//        返回获取到的文件名和后缀
        return s + substring;
    }

    @Override
    protected void validPicture(Object inputSource) {
        String url = (String) inputSource;
        ThrowUtils.throwIf(StrUtil.isBlank(url), ErrorCode.NOT_FOUND_ERROR, "文件地址不为空");
        // 1.验证url格式
        try {
            // 验证是否为合法的url格式
            new URL(url);
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件地址格式错误");
        }
        // 2.校验URL协议
        ThrowUtils.throwIf(!url.startsWith("http://") && !url.startsWith("https://"), ErrorCode.PARAMS_ERROR, "文件地址协议错误");
        // 3.发送HEAD请求，验证文件是否存在
        HttpResponse response = null;
        try {
            response = HttpUtil.createRequest(Method.HEAD, url).execute();
            // 未正常返回，则返回不需要继续执行后面的判断
            if (response.getStatus() != HttpStatus.HTTP_OK) {
                return;
            }
            // 检验文件的类型
            String contentType = response.header("Content-Type");
            if (StrUtil.isNotBlank(contentType)) {
                // 定义允许上传的文件类型
                final List<String> allowContentType = Arrays.asList("image/png", "image/jpeg", "image/jpg", "image/bmp", "image/gif", "image/webp");
                ThrowUtils.throwIf(!allowContentType.contains(contentType), ErrorCode.OPERATION_ERROR, "文件上传类型不支持");
            }
            // 检验文件的大小
            String contentLengthStr = response.header("Content-Length");
            if (StrUtil.isNotBlank(contentLengthStr)) {
                try {
                    final long TWO_MB = 1024 * 1024 * 5L; // 设置常量为5MB
                    // 将获取到的文件大小字符串转换为long类型方便后续比较
                    long contentLength = Long.parseLong(contentLengthStr);
                    ThrowUtils.throwIf(contentLength > TWO_MB, ErrorCode.PARAMS_ERROR, "上传文件大小不能超过2MB");
                } catch (NumberFormatException e) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小格式错误");
                }
            }
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }
}
